package com.ruoyi.bantong.service.impl;

import com.ruoyi.bantong.domain.*;
import com.ruoyi.bantong.mapper.*;
import com.ruoyi.bantong.service.IBtTaskRedbagService;
import com.ruoyi.bantong.service.IBtTaskService;
import com.ruoyi.bantong.service.IBtUserAccountRecordService;
import com.ruoyi.common.core.domain.entity.BtUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 版通申请Service业务层处理
 * 
 * @author laohei
 * @date 2021-01-26
 */
@Service
public class BtTaskRedbagServiceImpl implements IBtTaskRedbagService
{

    @Autowired
    private BtRedbagConfigMapper redbagConfigMapper;

    @Autowired
    private BtRedbagPollMapper btRedbagPollMapper;

    @Autowired
    private BtRedbagPollDetailsMapper detailsMapper;

    @Autowired
    private BtPlacecardApplyMapper applyMapper;

    @Autowired
    private IBtUserAccountRecordService userAccountRecordService;

    @Autowired
    private BtUserTicketMapper ticketMapper;


    /**
     * 定时红包开奖
     * 1判断当前时间是周几 1-6日开奖  7周开奖
     *
     * @return
     */
    @Override
    @Transactional
    public void openRedbagPool() {
        //查询可以加入的奖池
        BtRedbagPoll btRedbagPoll = btRedbagPollMapper.selectBtRedbagPollByStatus(0);
        if(StringUtils.isNull(btRedbagPoll)){
            return;
        }
        int type = btRedbagPoll.getType();
        BigDecimal updPercentageFee = btRedbagPoll.getUpdPercentageFee(); //修改后 总业绩
        Integer updPercentagePer = btRedbagPoll.getUpdPercentagePer(); //修改后 业绩百分比
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        BtRedbagConfig btRedbagConfig = redbagConfigMapper.selectBtRedbagConfigById(type);
        redbagConfigMapper.updateBtRedbagFromTemp();//同步配置表
        Integer openHour = btRedbagConfig.getOpenHour();//开奖时间
        Integer redbagFee = btRedbagConfig.getRedbagFee(); //中奖金额
        Integer openInterval = btRedbagConfig.getOpenInterval(); //开奖公布间隔
        Integer percentage = btRedbagConfig.getPercentage();//业绩百分比
        if(hour == openHour){
            btRedbagPollMapper.updateBtRedbagPoll(btRedbagPoll);
            Integer percentageSum = 0;
            //查询统计业绩
            if(type == 1){
                percentageSum = applyMapper.selectBtPlacecardApplySumDay();
            }else {
                Calendar cal  = Calendar.getInstance();
                cal.setFirstDayOfWeek(Calendar.MONDAY);
                cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                percentageSum = applyMapper.selectBtPlacecardApplySumWeek(cal.getTime());
            }
            btRedbagPoll.setPercentageFee(BigDecimal.valueOf(percentageSum));
            //如果有修改的值 使用修改的值
            if(updPercentageFee.compareTo(BigDecimal.ZERO) == 1){
                percentageSum = updPercentageFee.intValue();
            }
            //如果有修改的值 使用修改的值
            if(updPercentagePer > 0){
                percentage = updPercentagePer;
            }
            if(percentageSum != 0){
                BigDecimal percentageTemp = new BigDecimal(percentageSum).multiply(new BigDecimal(percentage)).divide(new BigDecimal(100));
                BigDecimal[] divide = percentageTemp.divideAndRemainder(new BigDecimal(redbagFee));
                btRedbagPoll.setWinNum(divide[0].intValue());
            }else{
                btRedbagPoll.setWinNum(0);
            }
            btRedbagPoll.setOpenTime(DateUtils.getNowDate());
            btRedbagPoll.setPublishTime(DateUtils.dateAddMinutes(null,openInterval));
            btRedbagPoll.setWinFee(BigDecimal.valueOf(redbagFee));
            btRedbagPoll.setPercentagePer(btRedbagConfig.getPercentage());
            this.open(btRedbagPoll);//开奖操作
        }else{
            return ;
        }
    }

    /**
     * 定时公布 红包开奖结果
     * 1查询已开奖并且 超过公布时间的bt_redbag_poll_details list
     *
     * @return
     */
    @Override
    @Transactional
    public void publishRedbagPool() {
        //查询待公布的 奖池
        BtRedbagPoll btRedbagPoll = btRedbagPollMapper.selectBtRedbagPollByStatus(2);
        if(StringUtils.isNull(btRedbagPoll)){
            return;
        }
        Integer type = btRedbagPoll.getType();//类型 1日 2周
        BigDecimal pollWinFee = btRedbagPoll.getWinFee();//中奖金额
        BtRedbagPollDetails detailsParam = new BtRedbagPollDetails();
        detailsParam.setRpId(btRedbagPoll.getRpId());
        detailsParam.setResult(1);
        //查询已中奖信息
        List<BtRedbagPollDetails> btRedbagPollDetails = detailsMapper.selectBtRedbagPollDetailsList(detailsParam);
        for(BtRedbagPollDetails details : btRedbagPollDetails){
            //发放奖励
            userAccountRecordService.updataUserAccount(details.getUserId(),pollWinFee,BigDecimal.ZERO,
                    details.getRpdId(),"bt_redbag_poll_details","in",type == 1 ? 13 : 14);
            Integer utId = details.getUtId();//奖券ID
            BtUserTicket ticket = ticketMapper.selectBtUserTicketById(utId);
            Integer winFee = ticket.getWinFee();//中奖总额
            Integer totalFee = ticket.getTotalFee();//可消耗额度
            winFee = new BigDecimal(winFee).add(pollWinFee).intValue();
            if(winFee >= totalFee){
                ticket.setStatus(2); //2已消耗
            }
            ticket.setWinFee(winFee);
            ticketMapper.updateBtUserTicket(ticket);
            BtRedbagPollDetails detailsTemp = new BtRedbagPollDetails();
            detailsTemp.setRpdId(details.getRpdId());
            detailsTemp.setUpdateTime(DateUtils.getNowDate());
            detailsTemp.setUpdateBy("system");
            detailsMapper.updateBtRedbagPollDetails(detailsTemp);
        }
        BtRedbagPoll btRedbagPollParam = new BtRedbagPoll();
        btRedbagPollParam.setRpId(btRedbagPoll.getRpId());
        btRedbagPollParam.setStatus(3);
        btRedbagPollParam.setUpdateTime(DateUtils.getNowDate());
        btRedbagPollParam.setUpdateBy("system");
        btRedbagPollMapper.updateBtRedbagPoll(btRedbagPollParam);
    }

    //开奖操作
    private void open(BtRedbagPoll btRedbagPoll){
        List<BtRedbagPollDetails> btRedbagPollDetails = detailsMapper.selectBtRedbagPollDetailsListNoBlack(btRedbagPoll.getRpId());
        btRedbagPoll.setTotal(btRedbagPollDetails.size());
        if(btRedbagPollDetails != null && btRedbagPollDetails.size() > 0){
            if(btRedbagPoll.getWinNum() > 0){
                Integer winNum = btRedbagPoll.getWinNum();
                if(winNum >= btRedbagPollDetails.size()){
                    winNum = btRedbagPollDetails.size();
                }
                for (int i = winNum; i >=1; i--) {
                    Random random = new Random();
                    Math.random();
                    //在数组大小之间产生一个随机数 j
                    int j = random.nextInt(btRedbagPollDetails.size() == 1 ? 1 : btRedbagPollDetails.size());
                    //取得list 中下标为j 的数据存储到 listRandom 中
                    BtRedbagPollDetails detailsWin = btRedbagPollDetails.get(j);
                    detailsWin.setResult(1);//中奖标志
                    detailsWin.setUpdateTime(DateUtils.getNowDate());
                    detailsMapper.updateBtRedbagPollDetails(detailsWin);
                    //把已取到的数据移除,避免下次再次取到出现重复
                    btRedbagPollDetails.remove(j);
                }
            }
        }
        btRedbagPoll.setStatus(2); //2已开奖
        btRedbagPollMapper.updateBtRedbagPoll(btRedbagPoll);
    }

    public static void main(String[] args) {
        BigDecimal[] divide = new BigDecimal(75).divideAndRemainder(new BigDecimal(50));

        System.out.println(divide[0] + "   "+ 75 /50);
    }
}
